package pers.lan.stack;

import java.util.Stack;

/**
 * @author <p><a href="mailto:1728209643@qq.com">XiaoSan</a>
 * @date 2019/9/5 3:30 PM
 */
public class LC_394 {
    public static void main(String[] args) {
        System.out.println(
                new LC_394().decodeString("3[a]2[bc]")
        );
    }

    public String decodeString(String s) {
        char[] chars = s.toCharArray();
        Stack<String> stack = new Stack<>();
        for (int i = chars.length - 1; i > -1; i--) {
            if (chars[i] == '[') {
                StringBuilder sb = new StringBuilder();
                while (!"]".equals(stack.peek())) {
                    sb.append(stack.pop());
                }
                stack.pop();
                i--;
                int j = i;
                for (; j > -1; j--) {
                    if (chars[j] < '0' || chars[j] > '9') {
                        break;
                    }
                }
                int i1 = Integer.parseInt(s.substring(j + 1, i + 1));
                i = j + 1;
                String s1 = sb.toString();
                for (int jj = 0; jj < i1 - 1; jj++) {
                    sb.append(s1);
                }
                stack.push(sb.toString());
            } else {
                stack.push(String.valueOf(chars[i]));
            }
        }
        return toString(stack);
    }

    private String toString(Stack<String> stack) {
        StringBuilder sb = new StringBuilder();
        while (!stack.empty()) {
            sb.append(stack.pop());
        }
        return sb.toString();
    }
}
